﻿#if UNITY_WEBGL
using System;
using System.IO;
using FibMatrix;
using FibMatrix.IO;
using UnityEditor;
using UnityEngine;
using WeChatWASM;


public partial class AutoBuilder
{
    [MenuItem("Tools/Export微信小游戏工程", false)]
    public static void BuildWeChatMiniGame()
    {
        Debug.Log("Perform WeiChat Build");
        CommonPreBuild();
        
        // 覆盖link.xml
        if (File.Exists("Assets/link_webgl.xml"))
        {
            Debug.Log("使用 Assets/link_webgl.xml 覆盖 Assets/link.xml");
            File.Copy("Assets/link_webgl.xml", "Assets/link.xml", true);
        }
        else
        {
            Debug.Log("不存在 Assets/link_webgl.xml，会使用 Assets/link.xml");
        }
        
        // 给主工程设置编译宏
        var extDefine = "";
        var additionMacro = Environment.GetEnvironmentVariable("ADDITION_MACRO");
        if (!string.IsNullOrEmpty(additionMacro))
        {
            additionMacro = additionMacro.Replace(" ", "");
            if (!additionMacro.StartsWith(";"))
            {
                extDefine = ";" + additionMacro;
            }
        }

        var group = BuildTargetGroup.WebGL;
        var buildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(group) + extDefine;
        PlayerSettings.SetScriptingDefineSymbolsForGroup(group, buildSymbols);

        Debug.Log(
            $"BuildWeChatMiniGame buildSymbols: {PlayerSettings.GetScriptingDefineSymbolsForGroup(group)}");
        
        // 设置debug参数
        var debugEnvString = Environment.GetEnvironmentVariable("IS_DEBUG");
        var isDebug = debugEnvString == "true";
        if (!string.IsNullOrEmpty(debugEnvString))
        {
            Debug.Log($"检测到环境设置 IS_DEBUG {isDebug}");
            WXConvertCore.config.CompileOptions.DevelopBuild = isDebug;
            WXConvertCore.config.CompileOptions.AutoProfile = isDebug;
            // 这个参数需要提供给
            EditorUserBuildSettings.development = isDebug;
        }

        var statStr = "Current\n";
        statStr += $"CompileOptions.DevelopBuild: {WXConvertCore.config.CompileOptions.DevelopBuild}\n";
        statStr += $"CompileOptions.AutoProfile: {WXConvertCore.config.CompileOptions.AutoProfile}\n";
        statStr += $"EditorUserBuildSettings.development: {EditorUserBuildSettings.development}\n";
        Debug.Log(statStr);
        
        PlayerSettings.SplashScreen.show = false;
        
        // 设置版本信息
        string distributePlatform = System.Environment.GetEnvironmentVariable("DISTRIBUTE_PLATFORM");
        if (string.IsNullOrEmpty(distributePlatform))
        {
            distributePlatform = "wechatminigame";
        }
        
        string productName = System.Environment.GetEnvironmentVariable("PRODUCT_NAME");
        if (!string.IsNullOrEmpty(productName))
        {
            PlayerSettings.productName = productName;
        }
        
        // webgl没有自增版本号写入的地方
        string versionNumberRaw = System.Environment.GetEnvironmentVariable("VERSIONCODE");
        Debug.Log($"小游戏不设置 VERSIONCODE: {versionNumberRaw} ");

        string versionString = System.Environment.GetEnvironmentVariable("GAME_VERSION");

        PlayerSettings.bundleVersion = versionString;
        
        // 打包时生成路径放到Library下，不放到默认目录下，避免Temp目录被Unity清理，用于编译失败时保留现场
        var genPath = FM_Mono.Editor.Generator.CombinePathForCSolution("Library", "ProjectBuildCache", "WxGameProj");
        if (!FM_Mono.Editor.Generator.CompileWxGameDll(genPath , true, isDebug))
            return;

        var origCdn = WXConvertCore.config.ProjectConf.CDN;
        // 去掉结尾的/，否则wx js预下载的文件会保存到把cdn url拆分开来的多段目录里，导致判断存在的失败
        while (!string.IsNullOrEmpty(origCdn) && origCdn.LastIndexOf('/') == origCdn.Length - 1)
        {
            origCdn = origCdn.Substring(0, origCdn.Length - 1);
        }

        // 添加平台路径给wx js
        if (!ResourceDevCfg.Instance.IsDebugStreamPlay() &&
            !origCdn.EndsWith(ResourcePathConst.WX_CDN_PLATFORM_PATH))
            WXConvertCore.config.ProjectConf.CDN = $"{origCdn}{ResourcePathConst.WX_CDN_PLATFORM_PATH}";

        if (WXConvertCore.DoExport(true) != WXConvertCore.WXExportError.SUCCEED)
            return;
        WeChatPostBuild();
        WXConvertCore.config.ProjectConf.CDN = origCdn;
        EditorUtility.SetDirty(WXConvertCore.config);
        AssetDatabase.SaveAssets();

        if (Application.isBatchMode)
        {
            string buildLockFile = Environment.GetEnvironmentVariable("BUILD_LOCK_PATH");
            if (!string.IsNullOrEmpty(buildLockFile) && File.Exists(buildLockFile))
            {
                File.Delete(buildLockFile);
            }
        }
    }

    [MenuItem("Tools/提取压缩小游戏bundle贴图", false)]
    static void WeChatPostBuild()
    {
        // 随包的启动文件，真机上只需要assetconfig，其他都下载，不需要bundleOffset
        string srcDir = Jelly.Editor.AssetBundle.JellyBundleAssetExporter.PACKAGE_FINAL_EXPORT_ROOT;
        string dstDir = Path.Combine(UnityUtil.GetEditorConf().ProjectConf.DST, WXConvertCore.miniGameDir,
            PackageManager.WXCodeSubPackageName);
        srcDir = Path.Combine(srcDir, AssetConfig.ASSET_CONFIG_FILE_NAME);
        dstDir = Path.Combine(dstDir, AssetConfig.ASSET_CONFIG_FILE_NAME);
        File.Copy(srcDir, dstDir, true);

        // 边玩边下的，方便本地开发设置cdn时所需文件存在
        srcDir = Jelly.Editor.AssetBundle.JellyBundleAssetExporter.HOTUPDATE_FINAL_EXPORT_ROOT;
        // js的preload会到$CDN_Path/StreamingAssets下找
        dstDir = Path.Combine(UnityUtil.GetEditorConf().ProjectConf.DST, WXConvertCore.webglDir,
            ResourcePathConst.WX_CACHEABLE_URL_TAG);
        CopyDirectory(srcDir, dstDir);


        // 纹理压缩
        Debug.Log("begin texture compression");
        WeChatWASMV1.WXTextureEditorWindow.CompressTexture();
        Debug.Log("end texture compression");

        Debug.Log("AutoBuilder Post Build done");
    }
}

#endif